package com.azt.front.action.common;

import com.azt.front.service.SitemapService;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 测试 sitemap 生成
 * Created by LiQZ on 2017/3/22.
 */
@Controller
public class SitemapAction {

    public static final Logger logger = LoggerFactory.getLogger(SitemapAction.class);

    @Autowired
    private SitemapService sitemapService;

    @Autowired
    private FreeMarkerConfig freeMarkerConfig;


    private LoadingCache<String,String> localCache = CacheBuilder.newBuilder()
            .maximumSize(10)
            .expireAfterAccess(1, TimeUnit.DAYS).build(new CacheLoader<String, String>() {
                @Override
                public String load(String key) throws Exception {
                    return generatorXml0(key);
                }
            });


    /**
     * 目前有
     *  product
     *  information
     *  category
     *  other
     *
     */
    @ResponseBody
    @RequestMapping(value = "sitemap/{type}.xml")
    public void sitemap(HttpServletResponse response, @PathVariable("type") String type) {
        long begin = System.currentTimeMillis();
        logger.info("begin to generator xml of {}", type);
        try {
            String xml = generatorXml(type);
            PrintWriter out = response.getWriter();
            response.setContentType("text/xml;charset=utf-8");
            out.println(xml);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("end with type {} time {}", type, System.currentTimeMillis() - begin);
    }

    public String generatorXml(String type) {
        logger.debug("generatorXml of type {}", type);
        try {
            return localCache.get(type);
        } catch (ExecutionException e) {
            logger.warn("generatorXml fail", e);
            e.printStackTrace();
        }
        return null;
    }

    private String generatorXml0(String type) throws IOException, TemplateException {
        Map<String, Object> params = sitemapService.getParams(type);
        Template template = freeMarkerConfig.getConfiguration().getTemplate("front/sitemap/" + type + ".xml");
        return FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
    }

}
